//
//  SurpriseShopOrderVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/25.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class SurpriseShopOrderVC: BaseViewController {
    
    var shopInfoStr : String!
    
    var allRemain = "0"

    var dataModel :  OrderSureDataModel?
    
    lazy var bottomView : OrderBottomView = {
        
        let temp = Bundle.main.loadNibNamed(self.StringFromClass(classType: OrderBottomView.self), owner: nil, options: nil)?.first as! OrderBottomView
        
        temp.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 72)
        
        temp.isHidden = true
        
        temp.delegate = self
        
        return temp
        
    }()
    


    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "订单确认"
        
        
        plainTableView.tableFooterView = bottomView
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: OrderSureSetionView.self), bundle: nil), forHeaderFooterViewReuseIdentifier: OrderSureSetionView.identifer())
        
        plainTableView.register(BaseTableViewCell.self, forCellReuseIdentifier: BaseTableViewCell.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: ShopCarOrderTopAddCell.self), bundle: nil), forCellReuseIdentifier: ShopCarOrderTopAddCell.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: OrderSwitchCell.self), bundle: nil), forCellReuseIdentifier: OrderSwitchCell.identifer())
        
        
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: OrderSelectCell.self), bundle: nil), forCellReuseIdentifier: OrderSelectCell.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: OrderBottomCell.self), bundle: nil), forCellReuseIdentifier: OrderBottomCell.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: OrderTotalPricCell.self), bundle: nil), forCellReuseIdentifier: OrderTotalPricCell.identifer())
        
        weak var weakSelf = self
        
        let NotifyChatMsgRecv = NSNotification.Name(rawValue:"KQDidPaySuccess")
        
        NotificationCenter.default.addObserver(forName: NotifyChatMsgRecv, object: nil, queue: OperationQueue.main) { (notice) in
            
            
            //            weakSelf?.navigationController?.popViewController(animated: true)
            
            QL1("快钱支付成功")
            
        }
        
        
        
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        plainTableView.mj_header.beginRefreshing()
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_index&a=member_state", parameters: nil) { [weak self] (responseObject, error) in
            
            if error == nil{
                
                
                if self?.dataModel != nil{
                    
                    let temp = responseObject?["datas"]?["paypwd_state"]
                    
                    
                    if temp != nil{
                        
                        
                        self?.dataModel?.paypwd_state = temp as! String
                        
                        
                    }
                    
                    
                    
                }
                
            }
            
            
        }
        
    }
    
    
    
    
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        
        
    }
    
    
    
    
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
}






extension SurpriseShopOrderVC{
    
    func loadData(){
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["cart_info"] = shopInfoStr as AnyObject
        parmeter["all_remain"] = allRemain as AnyObject
        
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_buy&a=one_dollar_buy_step1", parameters: parmeter) { [weak self] (responseObject, error)in
            
            if error == nil {
                
                
                let temp = responseObject?["datas"] as! [String : AnyObject]
                
                self?.dataModel = OrderSureDataModel(dic: temp)
                
                self?.dataModel?.GBPModels.removeAll()
                
                QL1(self?.dataModel?.paypwd_state)
                
                let number1 = Float(self!.dataModel!.available_bean) ?? 0
                let number2 = Float(self!.dataModel!.available_gold) ?? 0
                let number3 = Float(self!.dataModel!.available_predeposit) ?? 0
                
                if number1 > 0 {
                    
                    let tempModel = GBPInfoModel()
                    tempModel.available_bean = self!.dataModel!.available_bean
                    tempModel.available_bean_amount = self!.dataModel!.available_bean_amount
                    tempModel.bean_desc = self!.dataModel!.bean_desc
                    self?.dataModel?.GBPModels.append(tempModel)
                    
                    
                }
                
                if number2 > 0 {
                    
                    let tempModel = GBPInfoModel()
                    tempModel.available_gold = self!.dataModel!.available_gold
                    tempModel.available_gold_amount = self!.dataModel!.available_gold_amount
                    tempModel.gold_desc = self!.dataModel!.gold_desc
                    self?.dataModel?.GBPModels.append(tempModel)
                    
                }
                
                if number3 > 0 {
                    
                    let tempModel = GBPInfoModel()
                    tempModel.available_predeposit = self!.dataModel!.available_predeposit
                    tempModel.available_predeposit_amount = self!.dataModel!.available_predeposit_amount
                    tempModel.predeposit_desc = self!.dataModel!.predeposit_desc
                    self?.dataModel?.GBPModels.append(tempModel)
                    
                }
                
                
                
                self?.plainTableView.mj_header.endRefreshing()
                
                self?.plainTableView.reloadData()
                
                self?.bottomView.isHidden = false
                
            }else{
                
                self?.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
            }
        }
    }
}




extension SurpriseShopOrderVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModel == nil{
            
            return 0
        }
        
        return 3
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataModel == nil{
            
            return 0
        }
        
        
        switch section {
        case 0:
            return 1
        case 1:
            
            if dataModel!.useGoldBean == true {
                
                return dataModel!.GBPModels.count + 2
                
            } else {
                
                return dataModel!.GBPModels.count + 1
                
            }
            
        default:
            return dataModel!.payment_list.count
        }
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var tableCell : UITableViewCell? = nil
        
        if indexPath.section == 0 {
            
            let tempCell : BaseTableViewCell =  tableView.dequeueReusableCell(withIdentifier: BaseTableViewCell.identifer()) as! BaseTableViewCell
            
            
            tableCell = tempCell
  
            
        } else if indexPath.section == 1 {
            
            if indexPath.row == 0 {
                
                let tempCell : OrderTotalPricCell =  tableView.dequeueReusableCell(withIdentifier: OrderTotalPricCell.identifer()) as! OrderTotalPricCell
                
                tempCell.model = dataModel
                
                tempCell.index = indexPath
                
                tableCell = tempCell
                
            }else{
                
                if indexPath.row == dataModel!.GBPModels.count + 1 {
                    
                    let tempCell : OrderTotalPricCell =  tableView.dequeueReusableCell(withIdentifier: OrderTotalPricCell.identifer()) as! OrderTotalPricCell
                    
                    tempCell.model = dataModel
                    
                    tempCell.index = indexPath
                    
                    tableCell = tempCell
                    
                } else {
                    
                    let tempCell : OrderSwitchCell =  tableView.dequeueReusableCell(withIdentifier: OrderSwitchCell.identifer()) as! OrderSwitchCell
                    
                    tempCell.totalModel = dataModel
                    
                    tempCell.model = dataModel!.GBPModels[indexPath.row - 1]
                    
                    
                    tableCell = tempCell
                    
                    
                }
                
            }
            
            
            
            
        }else{
            
            
            
            let tempCell : OrderSelectCell =  tableView.dequeueReusableCell(withIdentifier: OrderSelectCell.identifer()) as! OrderSelectCell
            
            tempCell.models = dataModel?.payment_list
            
            tempCell.model = dataModel?.payment_list[indexPath.row]
            
            
            tableCell = tempCell
            
            
            
            
        }
        
        
        
        
        return tableCell!
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            
            return 0
            
        }else if indexPath.section == 1{
            
            if indexPath.row == 0 {
                
                return 44
                
            }else{
                
                if indexPath.row == dataModel!.GBPModels.count + 1 {
                    
                    return 44
                    
                    
                } else {
                    
                    
                    return 72
                    
                    
                }
                
            }
            
            
        }else{
            
            if indexPath.row == dataModel!.payment_list.count {
                
                return 72
                
                
            } else {
                
                return  72
                
            }
            
            
        }
        
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        
        switch section {
            
        case 0:
            
            return 0
            
        default:
            
            return 36
            
        }
        
    }
    
    
    
    
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        switch section {
            
        case 0:
            
            return nil
            
        default:
            
            let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: OrderSureSetionView.identifer()) as! OrderSureSetionView
            
            temp.section = section
            
            return temp
            
        }
        
        
        
        
    }
    
}







extension SurpriseShopOrderVC : OrderBottomViewDeleage{
    
    
    func orderBottomViewBtnDidTap(){
        
        
        
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["cart_info"] = shopInfoStr as AnyObject
        parmeter["all_remain"] = allRemain as AnyObject
        
        
        if dataModel?.useGoldBean == true {
            
            for item in dataModel!.GBPModels {
                
                if item.isOn == true {
                    
                    
                    let number1 = Float(item.available_bean) ?? 0
                    let number2 = Float(item.available_gold) ?? 0
                    let number3 = Float(item.available_predeposit) ?? 0
                    
                    
                    if number1 > 0 {
                        
                        parmeter["bean_pay"] = "1" as AnyObject
                        
                    }
                    
                    
                    if number2 > 0 {
                        
                        parmeter["gold_pay"] = "1" as AnyObject
                        
                    }
                    
                    
                    if number3 > 0 {
                        
                        parmeter["pd_pay"] = "1" as AnyObject
                        
                    }
                    
                }
                
            }
            
            
        }
        
        
        dataModel?.payWay = nil
        for item in dataModel!.payment_list {
            if item.isSelect == true {
                parmeter["payment_code"] = item.payment_code as AnyObject
                dataModel?.payWay = item.payment_code
            }
        }
        
        
        
        
        if dataModel?.useGoldBean == false && dataModel?.payWay == nil {
            
            
            alert(str: "请选择支付方式!")
            
            
            return
            
        }
        
        
        let needMoney = Float(dataModel!.needPayMoney) ?? 0
        
        if dataModel?.useGoldBean == true &&  needMoney > 0 && dataModel?.payWay == nil{
            
            alert(str: "请选择第三方支付方式!")
            
            
            return
        }
        
        
        
        
        
        
        if dataModel?.useGoldBean == true {
            
            if dataModel?.paypwd_state == "0" {
                
                setupPassword()
                
            } else {
                
                verifyPassword(bool: { (temp) in
                    
                    if temp == true{
                        
                        self.makeSurePay(pamer: parmeter)
                        
                        
                    }else{
                        
                        
                        QL1("密码错误")
                        
                        
                        
                        
                        
                    }
                })
                
            }
        } else {
            
            self.makeSurePay(pamer: parmeter)
            
        }
        
        
    }
    
    
    
    
    func alert(str : String) {
        
        let tempVC = UIAlertController(title: nil, message: str, preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "确定", style: .destructive) { (action) in
            
        }
        
        
        
        let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
            
            
        }
        
        tempVC.addAction(action2)
        tempVC.addAction(action1)
        
        present(tempVC, animated: true, completion: nil)
        
        
    }
    
    
    
    func setupPassword() {
        
        let tempVC = UIAlertController(title: nil, message: "您还未设置支付密码", preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "去设置", style: .default) { (action) in
            
            let temp = UpLoadIconController()
            
            temp.urlStr = self.dataModel!.set_paypwd_url
            
            self.navigationController?.pushViewController(temp, animated: true)
            
        }
        
        
        
        let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
            
            
        }
        
        tempVC.addAction(action2)
        tempVC.addAction(action1)
        
        present(tempVC, animated: true, completion: nil)
        
        
        
    }
    
    
    
    
    
    func verifyPassword(bool : @escaping (_ password : Bool) -> ()) {
        
        
        let tempVC = UIAlertController(title: nil, message: "请输入支付密码", preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "取消", style: .default) { (action) in
            
        }
        
        
        
        let action2 = UIAlertAction(title: "确定", style: .default) { (action) in
            
            let passwordTextField = tempVC.textFields?.first
            
            var parmeter  = [String : AnyObject]()
            
            parmeter["password"] = passwordTextField?.text as AnyObject
            
            NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_buy&a=check_password", parameters: parmeter, completionHandler: {(responseObject, error) in
                
                if error == nil{
                    
                    
                    bool(true)
                    
                    
                }else{
                    
                    SVProgressHUD.showError(withStatus: error?.domain)
                    
                    
                }
                
            })
            
            
        }
        
        
        tempVC.addTextField { (textField) in
            textField.keyboardType = .numberPad
            textField.isSecureTextEntry = true
            
            // 根据原有字符串生成属性字符串
            let placeholderStr = "请输入六位数字密码"
            
            let strM = NSMutableAttributedString(string:placeholderStr )
            
            strM.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 15), range:NSMakeRange(0, placeholderStr.characters.count))
            
            strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.colorWith(r: 199, g: 199, b: 205), range:NSMakeRange(0, placeholderStr.characters.count) )
            
            textField.attributedPlaceholder = strM
            
            
            
        }
        
        tempVC.addAction(action1)
        tempVC.addAction(action2)
        
        present(tempVC, animated: true, completion: nil)
        
        
    }
    
    
    
    
    
    func makeSurePay(pamer : [String : AnyObject]) {
        
        
        SVProgressHUD.show(withStatus: "订单确认中...")
        
        QL1(pamer)
        NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_buy&a=one_dollar_buy_step2", parameters: pamer) { [weak self] (responseObject, error) in
            
            
            
            if error == nil {
                SVProgressHUD.dismiss()
                
                let tempStr = responseObject?["datas"]?["order_payment_state"]
                
                if tempStr != nil{
                    
                    let temp = tempStr as! String
                    
                    if temp == "1" {
                        
                        self?.pushOrderVC()
                        
                        
                    } else {
                        
                        if self?.dataModel?.payWay == "alipay_app"{
                            
                            let aliPayStr = responseObject?["datas"]?["orderString"]
                            
                            if aliPayStr != nil{
                                
                                self?.AliPay(payStr: aliPayStr! as! String)
                                
                            }
                            
                            
                            
                        }else if self?.dataModel?.payWay == "wxpay_app"{
                            
                            let WXPayDic = responseObject?["datas"]?["wxpay_param"]
                            
                            if WXPayDic != nil{
                                
                                
                                self?.WXPay(dic: WXPayDic! as! [String : AnyObject])
                                
                                
                            }
                            
                            
                        }else{
                            
                            
                            let KQPayStr = responseObject?["datas"]?["orderString"]
                            
                            if KQPayStr != nil{
                                
                                self?.KQPay(payStr: KQPayStr! as! String)
                                
                            }
                            
                            
                        }
                        
                        
                    }
                    
                    
                    
                }
                
                
                
                
                
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
        }
        
        
        
        
    }
    
    
    
    func pushOrderVC() {
        
        let temp = AllOrderViewController()
        
        temp.type = .OneDollarType
        
        
        navigationController?.pushViewController(temp, animated: true)
        
    }
    
    
    
    
    func AliPay(payStr : String){
        
        
        AlipaySDK.defaultService().payOrder(payStr, fromScheme: "com.xiaojing.mall") { (_) in
            
        }
        
        
        
    }
    
    
    func WXPay(dic : [String : AnyObject]) {
        
        let temp  = PayReq()
        
        //由用户微信号和AppID组成的唯一标识，用于校验微信用户
        temp.openID = dic["appid"] as! String
        
        // 商家id，在注册的时候给的
        temp.partnerId = dic["partnerid"] as! String
        
        // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
        temp.prepayId  = dic["prepayid"] as! String
        
        // 根据财付通文档填写的数据和签名
        //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
        temp.package   = dic["pkg"] as! String
        
        // 随机编码，为了防止重复的，在后台生成
        temp.nonceStr  = dic["noncestr"] as! String
        
        // 这个是时间戳，也是在后台生成的，为了验证支付的
        let str = dic["timestamp"] as! String
        
        let temUin = UInt32(str)
        
        if temUin != nil {
            
            temp.timeStamp = temUin!
            
        }
        
        
        // 这个签名也是后台做的
        temp.sign = dic["sign"] as! String
        
        //发送请求到微信，等待微信返回onResp
        
        WXApi.send(temp)
        
        
        
    }
    
    
    func KQPay(payStr : String) {
        
        let temp = GoodsDetailController()
        
        temp.urlStr = payStr
        
        temp.hiddenBar = false
        
        temp.navigationItem.title = "快钱收银台"

        navigationController?.pushViewController(temp, animated: true)
        
        
    }
    
    
    
    
    
    
}

